import React, { useState, useEffect, useContext } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Keyboard,
  ScrollView,
  Alert,
} from "react-native";
import { AntDesign } from "@expo/vector-icons";
import { Entypo } from "@expo/vector-icons";
import TestQuesContext from "../../context/preparation/TestQuesContext";
import LoadingBar from "../../components/InterView/LoadingBar";

const AddTestQues = ({ navigation }) => {
  const { addTestQues, isTestQuesLoading } = useContext(TestQuesContext);
  const [title, setTitle] = useState(null); //题目标题
  const [options, setOptions] = useState([
    { label: "", id: 1, checked: false },
    { label: "", id: 2, checked: false },
    { label: "", id: 3, checked: false },
    { label: "", id: 4, checked: false },
  ]); //选项
  // const [correctOption, setCorrectOption] = useState([]); //正确选项

  const [keyboardIsOpen, setKeyboardIsOpen] = useState(false); //键盘
  const calType = ["单选", "多选"];
  const [selected, setSelected] = useState(0); //0表示单选singleSelect，1表示多选multiSelect

  const [choosedList, setChoosedList] = useState([]);

  const onPressItem = (id) => {
    // console.log("----进来了---", id);
    let customListNow = [...options];
    if (selected === 0) {
      for (const item in customListNow) {
        if (customListNow[item].id === id) {
          if (customListNow[item].checked != true) {
            customListNow[item].checked = true;
            let itemChoosed = customListNow[item];

            setChoosedList([itemChoosed]);
          }
        } else {
          customListNow[item].checked = false;
        }
      }
    } else {
      for (const item in customListNow) {
        if (customListNow[item].id === id) {
          if (customListNow[item].checked === false) {
            customListNow[item].checked = true;
            let itemChoosed = customListNow[item];

            setChoosedList([...choosedList, itemChoosed]);
          } else {
            customListNow[item].checked = false;
            let choosedListNow = choosedList.filter((item) => item.id !== id);

            setChoosedList(choosedListNow);
          }
        }
      }
    }
    setOptions(customListNow);
  };

  useEffect(() => {
    Keyboard.addListener("keyboardDidShow", _keyboardDidShow);
    Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

    // cleanup function
    return () => {
      Keyboard.removeAllListeners("keyboardDidShow");
      Keyboard.removeAllListeners("keyboardDidHide");
    };
  }, []);

  const _keyboardDidShow = () => {
    setKeyboardIsOpen(true);
  };

  const _keyboardDidHide = () => {
    setKeyboardIsOpen(false);
  };

  const deleteOption = (id) => {
    //删除选项后需重新排列id
    const preOptions = options.filter((t_item, t_index) => t_item.id !== id);
    const nowOptions = preOptions.map((item, index) => {
      item.id = index + 1;
      return item;
    });
    setOptions(nowOptions);
    // console.log("----删除后选项", nowOptions);
    const nowChoosed = nowOptions.filter((item) => item.checked !== false);

    // console.log("----删除后选中选项", nowChoosed);
    setChoosedList(nowChoosed);

    // console.log("删除前-----", choosedList);
    // const nowChoosed = choosedList.filter(
    //   (t_item, t_index) => t_item.id !== id
    // );
    // console.log("----删除后选中", nowChoosed);
    // setChoosedList(nowChoosed);
  };

  const onConfirm = () => {
    Alert.alert("提示", "确定要提交吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: async () => {
          if (choosedList.length === 0) {
            Alert.alert("提示", "请选择正确答案", [{ text: "确定" }]);
            return;
          }
          let correctOption = [];
          choosedList.map((item) => correctOption.push(item.id));

          let item = {
            question: title,
            options: options,
            correntOption: correctOption,
            type: selected === 0 ? "singleSelect" : "multiSelect",
          };
          addTestQues(item, () => {
            navigation.navigate("TestQuesManage");
          });
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isTestQuesLoading} />
      <ScrollView style={{ flex: 1 }}>
        <View>
          <View style={styles.top}>
            <View style={styles.title}>
              <Text style={styles.titleIcon}>* </Text>
              <Text style={styles.titleText}>标题</Text>
            </View>
            <TextInput
              style={styles.inputBox}
              multiline={true}
              value={title}
              placeholder="请输入题目"
              onChangeText={(text) => {
                setTitle(text);
              }}
            />
          </View>
          <View
            style={[
              styles.top,
              { flexDirection: "row", justifyContent: "space-between" },
            ]}
          >
            <View style={{ flexDirection: "row" }}>
              <Text style={styles.titleIcon}>* </Text>
              <Text style={styles.titleText}>类型</Text>
            </View>
            <View style={{ flexDirection: "row" }}>
              {calType.map((tag, index) => {
                return (
                  <TouchableOpacity
                    style={{ marginLeft: 10 }}
                    key={index}
                    onPress={() => {
                      setSelected(index);
                      console.log("选择了---", index);
                    }}
                  >
                    <Text
                      style={
                        index === selected ? styles.selectedTag : styles.tag
                      }
                    >
                      {tag}
                    </Text>
                  </TouchableOpacity>
                );
              })}
            </View>
          </View>
          <View style={styles.context}>
            <View
              style={{ flexDirection: "row", justifyContent: "space-between" }}
            >
              <View style={styles.title}>
                <Text style={styles.titleIcon}>* </Text>
                <Text style={styles.titleText}>选项</Text>
              </View>
              <Text style={styles.titleText}>答案</Text>
            </View>
            {options.map((item, index) => {
              return (
                <View style={styles.deleteOption} key={index}>
                  <TouchableOpacity
                    style={{ marginRight: 10 }}
                    onPress={() => deleteOption(item.id)}
                  >
                    <AntDesign name="minuscircle" size={18} color="red" />
                  </TouchableOpacity>
                  <View style={{ flex: 1 }}>
                    <TextInput
                      style={[styles.inputLine, { padding: 5 }]}
                      multiline={true}
                      value={item.label}
                      placeholder="请输入选项"
                      onChangeText={(text) => {
                        let option = {
                          label: text,
                          id: item.id,
                          checked: item.checked,
                        };
                        // console.log("修改后----", option);
                        setOptions((preOptions) => {
                          return preOptions.map((t_item, t_index) => {
                            return index === t_index ? option : t_item;
                          });
                        });
                      }}
                    />
                  </View>
                  <TouchableOpacity
                    onPress={() => onPressItem(item.id)}
                    style={{ paddingLeft: 10 }}
                  >
                    <AntDesign
                      name="checksquare"
                      size={18}
                      color={!item.checked ? "#D8D8D8" : "green"}
                    />
                  </TouchableOpacity>
                </View>
              );
            })}
            <View style={{ flexDirection: "row" }}>
              <TouchableOpacity
                onPress={() => {
                  setOptions([
                    ...options,
                    { label: "", id: options.length + 1, checked: false },
                  ]);
                }}
              >
                <View style={styles.deleteOption}>
                  <View>
                    <AntDesign name="pluscircle" size={18} color="#41C3EE" />
                  </View>
                  <Text style={styles.addOptionText}>添加选项</Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </ScrollView>

      {!keyboardIsOpen && (
        <View style={styles.btnBox}>
          <TouchableOpacity
            style={styles.backBtn}
            onPress={() => navigation.goBack()}
          >
            <Text style={{ color: "#41C3EE", fontSize: 16 }}>取消</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.submitBtn}
            onPress={() => onConfirm()}
          >
            <Text style={{ color: "#fff", fontSize: 16 }}>确认</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white",
  },
  top: {
    borderBottomColor: "#eee",
    borderBottomWidth: 7,
    padding: 16,
  },
  title: {
    flexDirection: "row",
    marginBottom: 10,
  },
  titleIcon: { color: "red", fontSize: 16 },
  titleText: { color: "#aaa", fontSize: 16 },
  inputBox: {
    borderColor: "#ddd",
    borderWidth: 1,

    borderRadius: 2,
    padding: 10,
  },
  inputLine: {
    borderBottomColor: "#ddd",
    borderBottomWidth: 1,

    padding: 10,
  },
  context: {
    padding: 16,
    borderBottomColor: "#eee",
    borderBottomWidth: 7,
  },
  deleteOption: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 15,
  },

  addOptionText: {
    color: "#41C3EE",
    paddingLeft: 14,
    fontSize: 16,
  },
  btnBox: {
    flexDirection: "row",
    justifyContent: "space-between",
    padding: 16,
  },
  backBtn: {
    borderWidth: 1,
    borderColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
    flex: 1,
    marginRight: 20,
    // width: 100,
  },
  submitBtn: {
    backgroundColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
    flex: 2,
    // width: 200,
  },
  selectedTag: {
    borderWidth: 1,
    borderColor: "#41C3EE",
    padding: 1,
    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 10,
    color: "#41C3EE",
  },
  tag: {
    borderWidth: 1,
    borderColor: "#d1d1d6",
    padding: 1,
    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 10,
    color: "#d1d1d6",
    fontSize: 14,
  },
});

export default AddTestQues;
